package com.john.cloud.feigin.fallback;

import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: JohnCoding
 * @Description:  自定义的fallback方法，
 * 并且将其指定给某个route来实现该route访问出问题的熔断处理。
 * 默认有两个方法，一个用来指明熔断拦截哪个服务，一个定制返回内容。
 * @date: 2020/7/3 10:13
 */
@Component
public class ProducerFallback implements FallbackProvider {

    /**
     * 用来指明熔断拦截哪个服务
     * @return
     */
    @Override
    public String getRoute() {
        //指定要处理的 service。
        return "Spring-boot-rabbitmq";
    }

    /**
     * 定制返回内容。
     * @param route
     * @param cause
     * @return
     */
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        if(null != cause && null != cause.getCause()){
            System.out.println(cause.getCause().getMessage());
        }
        return fallbackResponse();
    }


    /**
     * 配置自定义Http返回类
     * @return
     */
    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return 200;
            }

            @Override
            public String getStatusText() throws IOException {
                return "OK";
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream("The service is unavailable.".getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                //appliciontContentType - > json
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
}
